package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.FragmentAdapter;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.fragment.LocalAlbumImportFragment;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 导入手机相册界面
 */
public class LocalAlbumImportActivity extends BaseActivity {
    private Toolbar mToolbar;
    private ViewPager vp_import;
    private ProgressDialog mProgressDialog;             // 进度条
    private boolean is3GType = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_local_import_manage);
        initView();
    }

    private void initView() {
        mToolbar = ((Toolbar) findViewById(R.id.local_manage_toolbar));
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        vp_import = ((ViewPager) findViewById(R.id.vp_import));
        ArrayList<Fragment> fragment = new ArrayList<>();
        fragment.add(new LocalAlbumImportFragment());
        FragmentAdapter adapter =
                new FragmentAdapter(getSupportFragmentManager(), fragment);
        vp_import.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_import, menu);
        MenuItem action_import = menu.findItem(R.id.action_import);
        action_import.getActionView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadPhoto(false);
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    private void uploadPhoto(boolean isPause) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                is3GType = true;
            } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                is3GType = false;
            }
        }
        if (!is3GType) {
            showToast("请在WIFI环境下上传图片");
            return;
        }
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        //选择好照片后点击导入将要上传的照片url存入本地
        //跳转进度条界面
        if (SelectedImg.mSelectedImage.size() == 0) {
            showToast("未选择图片");
            return;
        }
        String s = toJson();
        SharedPreferences sp = getSharedPreferences("nullUpkey", Context.MODE_PRIVATE);
        int picNumber = sp.getInt("picNumber", 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("nullUpkey", s);
        edit.putInt("totalPic", picNumber + SelectedImg.mSelectedImage.size());
        edit.commit();
        startActivity(new Intent(this, ImporProgressActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        finish();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private String toJson() {
        JSONObject jsonObject1 = new JSONObject();
        JSONArray jsonArray1 = new JSONArray();
        //将图片数据转换成json字符串
        Iterator<Map.Entry<String, List<String>>> it = SelectedImg.dateUrl.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, List<String>> entry = it.next();
            String key = entry.getKey();
            try {
                jsonObject1.put("date", key);
                List<String> value = entry.getValue();
                String url = null;
//                if (value.size()!=0){
//                    Log.d("yuhao", "strings="+value.get(0));
//                    Log.d("yuhao", "strings="+value.get(1));
//                }
                for (int i = 0; i < value.size(); i++) {
                    String strings = value.get(i);
                    if (url == null) {
                        url = strings;
                    } else {
                        url = url + "," + strings;
                    }
                }
                jsonObject1.put("photo", url);
                jsonArray1.put(jsonObject1);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonArray1.toString();
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
